package com.wayne.testapp.service;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.wayne.testapp.R;
import com.wayne.testapp.utils.MUtils;
import com.wayne.testapp.utils.PreUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wayne on 2016/06/29.
 */
public class DownloadService extends Service {
    private DownloadManager dm;
    private long task;
    private BroadcastReceiver receiver;
    private String url;
    //监听器
    private DownloadChangeObserver downloadObserver;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        url = intent.getStringExtra("url");
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                String currTime = PreUtil.getInstance(getApplicationContext()).getString("time","");
                File file = new File(Environment.getExternalStorageDirectory() + "/download/"+currTime+".apk");
                intent.setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");
                startActivity(intent);
                stopSelf();
            }
        };

        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        startDownload();
        return Service.START_STICKY;
    }


    @Override
    public void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    private void startDownload() {
        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(
                Uri.parse(url));
        request.setTitle("什马金融");
        request.setDescription("什马金融正在全速下载");
        request.setMimeType("application/vnd.android.package-archive");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String time = sdf.format(date);
        PreUtil.getInstance(this).putString("time",time);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, time+".apk");
        task = dm.enqueue(request);

        //打开监听器
        downloadObserver = new DownloadChangeObserver(null);
        getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

        //打开窗口
        openDialog();

    }

    private AlertDialog dialog;
    private ContentLoadingProgressBar pb;
    private TextView tv_download;

    private void openDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("玩命下载中");

        View view = View.inflate(this, R.layout.dialog_download, null);
        pb = (ContentLoadingProgressBar) view.findViewById(R.id.pb);
        tv_download = (TextView) view.findViewById(R.id.tv_download);
        builder.setView(view);
        dialog = builder.create();
        dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    class DownloadChangeObserver extends ContentObserver {


        public DownloadChangeObserver(Handler handler) {
            super(handler);
            // TODO Auto-generated constructor stub
        }


        @Override
        public void onChange(boolean selfChange) {
            queryDownloadStatus();
        }


    }


    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(task);
        Cursor c = dm.query(query);
        if (c != null && c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));

            int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);
            int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
            int fileSizeIdx =
                    c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            int bytesDLIdx =
                    c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
            String title = c.getString(titleIdx);
            //当前文件总长
            int fileSize = c.getInt(fileSizeIdx);
            //已有字节
            int bytesDL = c.getInt(bytesDLIdx);

            // Translate the pause reason to friendly text.
            int reason = c.getInt(reasonIdx);
            StringBuilder sb = new StringBuilder();
            sb.append(bytesDL).append("/").append(fileSize);

            if (pb != null) {
                pb.setMax(fileSize);
            }
            // Display the status
            tv_download.setText(sb.toString());

            Log.d("tag", sb.toString());
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    Log.v("tag", "STATUS_PAUSED");
                case DownloadManager.STATUS_PENDING:
                    Log.v("tag", "STATUS_PENDING");
                case DownloadManager.STATUS_RUNNING:
                    //正在下载，不做任何事情
                    Log.v("tag", "STATUS_RUNNING");
                    if (pb != null) {
                        pb.setProgress(bytesDL);
                        tv_download.setText(sb);
                        tv_download.invalidate();
                    }

                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //完成
                    Log.v("tag", "下载完成");
                    closeDialog();
                    break;
                case DownloadManager.STATUS_FAILED:
                    //清除已下载的内容，重新下载
                    Log.v("tag", "STATUS_FAILED");
                    if (dm != null) {
                        dm.remove(task);
                    }
                    closeDialog();
                    break;
            }
        }
    }

    private void closeDialog() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }


}
